package com.googlecode.garbagecan.test.socket.nio;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.SocketChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class MyClient1 {
	
	private final static Logger logger = Logger.getLogger(MyClient1.class.getName());
	
	public static void main(String[] args) throws Exception {
		for (int i = 0; i < 10; i++) {
			SocketChannel socketChannel = null;
			Socket socket = null;
			GZIPOutputStream gzipos = null;
			ObjectOutputStream oos = null;
			GZIPInputStream gzipis = null;
			ObjectInputStream ois = null;
			
			try {
				socketChannel = SocketChannel.open();
				SocketAddress socketAddress = new InetSocketAddress("localhost", 10000);
				socketChannel.connect(socketAddress);
				socket = socketChannel.socket();
				socket.setSoTimeout(10 * 1000);
				
				gzipos = new GZIPOutputStream(socket.getOutputStream());
				oos = new ObjectOutputStream(gzipos);
				MyRequestObject myRequestObject = new MyRequestObject("request_" + i, "request_" + i);
				oos.writeObject(myRequestObject);
				oos.flush();
				gzipos.finish();
				
				gzipis = new GZIPInputStream(socket.getInputStream());
				ois = new ObjectInputStream(gzipis);
				Object obj = ois.readObject();
				if (obj != null) {
					MyResponseObject myResponseObject = (MyResponseObject)obj;
					logger.log(Level.INFO, myResponseObject.toString());
				}
			} catch(IOException ex) {
				logger.log(Level.SEVERE, null, ex);
			} finally {
				try {
					ois.close();
				} catch(Exception ex) {}
				try {
					oos.close();
				} catch(Exception ex) {}
				try {
					socket.close();
				} catch(Exception ex) {}
				try {
					socketChannel.close();
				} catch(Exception ex) {}
			}
		}
	}
}
